package com.heimdallr.config;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import com.heimdallr.util.AppUtils;
import com.heimdallr.util.SerializationUtils;
import com.heimdallr.util.cache.CachePool;
import com.heimdallr.util.cache.LocalCache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author user
 */
@Component
public class RedisSessionDao extends AbstractSessionDAO {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final Logger log= LoggerFactory.getLogger(RedisSessionDao.class);
    private static LocalCache localCache = CachePool.getInstance().getCache(CachePool.cacheKind.session);


    @Override
    public void update(Session session) throws UnknownSessionException {

        try {

            String cacheStr = new String(SerializationUtils.jdkserialize(session),SerializationUtils.charsetCode);
            String sessionId = session.getId().toString();
            localCache.putValue(sessionId,cacheStr,60*60);
            redisTemplate.opsForValue().set(sessionId,cacheStr,2,TimeUnit.HOURS);

        } catch (Exception e) {
            log.error("update session error ",e);
        }
    }

    @Override
    public void delete(Session session) {

        try {
            redisTemplate.delete(session.getId().toString());
            localCache.remove(session.getId().toString());
        } catch (Exception e) {
            log.error("delete session error ",e);
        }

    }

    @Override
    public Collection<Session> getActiveSessions() {
        return Collections.emptySet();
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);

        try {

            String cacheStr = new String(SerializationUtils.jdkserialize(session),SerializationUtils.charsetCode);

            //存两份，一份redis，一份本地，优先本地
            localCache.putValue(sessionId.toString(),cacheStr,60*60);
            redisTemplate.opsForValue().set(sessionId.toString(),cacheStr,2,TimeUnit.HOURS);

        } catch (Exception e) {
            log.error("doCreate session error ",e);
        }

        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {

        Session session = null;
        try {
            String serializedSession = "";

            if(localCache.containsKey(sessionId.toString())){
                serializedSession = (String) localCache.getValue(sessionId.toString());
            }else{
                serializedSession = redisTemplate.opsForValue().get(sessionId.toString());
            }

            if(AppUtils.isNotNull(serializedSession)){
                session = (Session) SerializationUtils.jdkdeserialize(serializedSession.getBytes(SerializationUtils.charsetCode));
            }
        } catch (Exception e) {
            log.error("doReadSession session error ",e);
        }
        return session;
    }

}
